package com.asset.dispoal.business.bsEvidenceRecognition.service.commom;

import com.asset.dispoal.business.bsAgreement.domain.db.entity.AgreementStateRecord;
import com.asset.dispoal.business.bsAgreement.domain.db.mapper.AgreementMapper;
import com.asset.dispoal.business.bsCase.domain.db.entity.CaseIdCardNum;
import com.asset.dispoal.business.bsCase.domain.db.entity.CaseStateRecord;
import com.asset.dispoal.business.bsCase.domain.db.mapper.BsCaseMapper;
import com.asset.dispoal.business.bsEvidenceRecognition.domain.db.entity.MatchSuccessEvidence;
import com.asset.dispoal.business.bsEvidenceRecognition.domain.db.entity.RemoveEvidenceContract;
import com.asset.dispoal.business.bsEvidenceRecognition.domain.db.mapper.BusinessDataManageMapper;
import com.asset.dispoal.business.bsEvidenceRecognition.dto.ContractEvidenceResponse;
import com.asset.dispoal.business.match.dto.RefreshCaseStateRequest;
import com.asset.dispoal.commom.menus.AgreementCaseSateMenu;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.id.BaseIdeable;
import tech.mhuang.pacebox.core.util.CollectionUtil;
import tech.mhuang.pacebox.core.util.StringUtil;
import tech.mhuang.pacebox.springboot.core.local.GlobalHeaderThreadLocal;
import tech.mhuang.pacebox.springboot.protocol.Result;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Component
@Slf4j
public class RefreshCaseStateCommand implements BaseCommand<RefreshCaseStateRequest, Result> {

    @Autowired
    private BsCaseMapper caseMapper;

    @Autowired
    private AgreementMapper agreementMapper;
    @Autowired
    private BusinessDataManageMapper businessDataManageMapper;

    @Autowired
    private BaseIdeable<String> ideable;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Result execute(RefreshCaseStateRequest request) {
        String userId = GlobalHeaderThreadLocal.getOrException().getUserId();
        // 查询所有集证状态下的合同明细
        List<CaseIdCardNum> caseIdCardNumList = caseMapper.queryCaseIdNumByAssetInstBatchId(request.getAssetInstBatchId());
        List<Map<String, String>> mapList = businessDataManageMapper.queryDataDetail(request.getAssetInstBatchId());
        List<Map<String, String>> queryResult = businessDataManageMapper.queryResultByGather(request.getAssetInstBatchId(), mapList);
        Map<String, List<CaseIdCardNum>> caseIdCardNumMap = caseIdCardNumList.stream().collect(Collectors.groupingBy(CaseIdCardNum::getIdCard));
        if ("2".equals(request.getUseType())) {
            AgreementCaseSateMenu delivery = AgreementCaseSateMenu.WAIT_DELIVERY;
            Map<String, List<Map<String, String>>> groupedMap = queryResult.stream().collect(Collectors.groupingBy(e -> e.get("borrowerIdcard")));
            for (Map.Entry<String, List<Map<String, String>>> entry : groupedMap.entrySet()) {
                List<Map<String, String>> agreementDataList = entry.getValue();
                String idCard = entry.getKey();
                String caseId = caseIdCardNumMap.get(idCard).get(0).getId();
                for (Map<String, String> agreementData : agreementDataList) {
                    String agreementId = agreementData.get("contractId");
                    AgreementStateRecord agreementStateRecord = new AgreementStateRecord();
                    agreementStateRecord.setId(ideable.generateId());
                    agreementStateRecord.setOldState(AgreementCaseSateMenu.GATHER.getLabel());
                    agreementStateRecord.setNewState(delivery.getLabel());
                    agreementStateRecord.setContractId(agreementId);
                    agreementStateRecord.setCreateUser(userId);
                    agreementMapper.insertStateRecord(agreementStateRecord);
                    agreementMapper.updateAgreementState(agreementId, delivery.getLabel(), userId);
                }
                CaseStateRecord caseStateRecord = new CaseStateRecord();
                caseStateRecord.setId(ideable.generateId());
                caseStateRecord.setOldState(AgreementCaseSateMenu.GATHER.getLabel());
                caseStateRecord.setNewState(delivery.getLabel());
                caseStateRecord.setCaseId(caseId);
                caseStateRecord.setCreateUser(userId);
                caseMapper.insertStateRecord(caseStateRecord);
                caseMapper.updateCaseState(caseId, delivery.getLabel(), delivery.getState(), userId);
            }
        } else {
            // 查询当前所有匹配上的原始证据
            List<MatchSuccessEvidence> matchSuccessEvidenceList = businessDataManageMapper.queryMatchSuccessEvidence(request.getAssetInstBatchId(), null, "0");
            //查询批次下全部删除的证据id和合同id
            List<RemoveEvidenceContract> removeEvidenceContractList = businessDataManageMapper.queryRemoveEvidenceContract(request.getAssetInstBatchId(), null, "0");
            //查询所有的原始证据
            List<ContractEvidenceResponse> evidenceResponseList = businessDataManageMapper.queryEvidenceTypeByAssetInstBatchId(request.getAssetInstBatchId(), null, "0");
            Map<String, List<Map<String, String>>> groupedMap = queryResult.stream().collect(Collectors.groupingBy(e -> e.get("borrowerIdcard")));
            Map<String, List<MatchSuccessEvidence>> evidenceTypeSuccessMap = matchSuccessEvidenceList.stream().collect(Collectors.groupingBy(MatchSuccessEvidence::getEvidenceTypeId));
            Map<String, List<RemoveEvidenceContract>> removeEvidenceContractMap = removeEvidenceContractList.stream().collect(Collectors.groupingBy(RemoveEvidenceContract::getEvidenceTypeId));
            AgreementCaseSateMenu delivery = AgreementCaseSateMenu.WAIT_DELIVERY;
            for (Map.Entry<String, List<Map<String, String>>> entry : groupedMap.entrySet()) {
                String idCard = entry.getKey();
                String caseId = caseIdCardNumMap.get(idCard).get(0).getId();
                List<Map<String, String>> agreementDataList = entry.getValue();
                boolean checkCase = Boolean.TRUE;
                // 根据人循环对应合同
                for (Map<String, String> agreementData : agreementDataList) {
                    String agreementId = agreementData.get("contractId");
                    boolean checkAgreementType = Boolean.TRUE;
                    //合同下的证据类型
                    for (ContractEvidenceResponse contractEvidenceResponse : evidenceResponseList) {
                        boolean checkEvidenceType = Boolean.FALSE;
                        //当前类型
                        List<MatchSuccessEvidence> evidenceTypeList = evidenceTypeSuccessMap.get(contractEvidenceResponse.getId());
                        //删除的证据类型
                        List<RemoveEvidenceContract> removeEvidenceTypeList = removeEvidenceContractMap.get(contractEvidenceResponse.getId());
                        List<MatchSuccessEvidence> matchSuccessEvidences = evidenceTypeList;
                        if (CollectionUtil.isNotEmpty(removeEvidenceTypeList)) {
                            Set<String> removeEvidenceIdSet = removeEvidenceTypeList.stream().filter(removeEvidenceType -> agreementData.get("contractId").equals(removeEvidenceType.getContractId())).map(RemoveEvidenceContract::getEvidenceId).collect(Collectors.toSet());

                            matchSuccessEvidences = evidenceTypeList.stream().filter(evidenceType -> !removeEvidenceIdSet.contains(evidenceType.getEvidenceId())).collect(Collectors.toList());
                        }
                        if (CollectionUtil.isEmpty(matchSuccessEvidences)) {
                            checkAgreementType = Boolean.FALSE;
                            break;
                        }
                        for (MatchSuccessEvidence matchSuccessEvidence : matchSuccessEvidences) {
                            //无需匹配的证据直接返回当前成功
                            if (StringUtil.isEmpty(matchSuccessEvidence.getAlias())) {
                                checkEvidenceType = Boolean.TRUE;
                                break;
                            }
                            //证据匹配上的返回成功
                            try {
                                if (agreementData.get(matchSuccessEvidence.getAlias()).equals(matchSuccessEvidence.getResult())) {
                                    checkEvidenceType = Boolean.TRUE;
                                    break;
                                }
                            } catch (Exception ignore) {
                            }


                        }
                        if (!checkEvidenceType) {
                            checkAgreementType = Boolean.FALSE;
                            break;
                        }
                    }
                    if (!checkAgreementType) {
                        //如果有其他合同能找到的变更合同状态，不改变案件状态
                        checkCase = Boolean.FALSE;
                    } else {
                        //合同状态和历史消息编辑
                        AgreementStateRecord agreementStateRecord = new AgreementStateRecord();
                        agreementStateRecord.setId(ideable.generateId());
                        agreementStateRecord.setOldState(AgreementCaseSateMenu.GATHER.getLabel());
                        agreementStateRecord.setNewState(delivery.getLabel());
                        agreementStateRecord.setContractId(agreementId);
                        agreementStateRecord.setCreateUser(userId);
                        agreementMapper.insertStateRecord(agreementStateRecord);
                        agreementMapper.updateAgreementState(agreementId, delivery.getLabel(), userId);
                    }
                }
                if (checkCase) {
                    //案件状态和历史消息编辑
                    CaseStateRecord caseStateRecord = new CaseStateRecord();
                    caseStateRecord.setId(ideable.generateId());
                    caseStateRecord.setOldState(AgreementCaseSateMenu.GATHER.getLabel());
                    caseStateRecord.setNewState(delivery.getLabel());
                    caseStateRecord.setCaseId(caseId);
                    caseStateRecord.setCreateUser(userId);
                    caseMapper.insertStateRecord(caseStateRecord);
                    caseMapper.updateCaseState(caseId, delivery.getLabel(), delivery.getState(), userId);
                }
            }
        }

        return Result.ok();
    }
}
